/* eslint-disable radix */
import React, { useState, useRef } from 'react'
import { imgConfig } from './config'
import _ from 'lodash'

const Magnifying = () => {
  const [bar, setBar] = useState('')
  const [magShowIng, setMagShowIng] = useState('')
  const [img, setImg] = useState('')
  const glass = useRef(null)
  const magIng = useRef(null)

  const onMouseEnter = (e) => {
    setBar('bar')
    setMagShowIng('mag-show-ing')
  }
  const onMouseLeave = () => {
    setBar('')
    setMagShowIng('')
  }
  const getImgBackgroundSize = (ele) => {
    const obj = {}
    const w = window.getComputedStyle(ele).backgroundSize
    const sizeArr = w.split(' ')

    if (sizeArr.length === 1) {
      obj.width = parseInt(sizeArr[0])
      obj.height = parseInt(sizeArr[0])
    } else {
      obj.width = parseInt(sizeArr[0])
      obj.height = parseInt(sizeArr[1])
    }
    return obj
  }
  const onMouseMove = (e) => {
    const Bar = document.querySelector('#bar')
    const mapIng = magIng.current
    const MapIngoffsetLeft = mapIng.offsetLeft
    const MapIngoffsetTop = mapIng.offsetTop

    let x = e.pageX - MapIngoffsetLeft - Bar.offsetWidth / 2 - 10
    let y = e.pageY - MapIngoffsetTop - Bar.offsetHeight / 2 - 10
    if (x < 0) {
      x = 0
    }
    if (x > mapIng.clientWidth - Bar.offsetWidth - 0) {
      x = mapIng.clientWidth - Bar.offsetWidth - 0
    }
    if (y < 0) {
      y = 0
    }
    if (y > mapIng.clientHeight - Bar.offsetHeight - 0) {
      y = mapIng.clientHeight - Bar.offsetHeight - 0
    }
    Bar.style.left = x + 'px'
    Bar.style.top = y + 'px'

    // 背景图片的定位 = 背景图片的宽/高 * 遮盖层的定位 /  显示区域的宽/高

    let glassX =
      (getImgBackgroundSize(glass.current).width * x) /
      magIng.current.clientWidth
    let glassY =
      (getImgBackgroundSize(glass.current).height * y) /
      magIng.current.clientHeight

    glass.current.style.backgroundPosition = `-${glassX}px -${glassY}px`
  }
  const imgClick = (img) => {
    setImg(img)
  }
  return (
    <div>
      {_.map(imgConfig, (item, key) => {
        return (
          <img
            key={key}
            src={item.small}
            className="img-url"
            alt="侯德康"
            onClick={() => imgClick(item.big)}
          />
        )
      })}
      <div className="mag">
        <div
          className="mag-ing"
          onMouseEnter={onMouseEnter}
          onMouseMove={onMouseMove}
          onMouseLeave={onMouseLeave}
          ref={magIng}
        >
          <img src={img} alt="请选择一张图片" className="img-ing" />
          <div className={bar} id="bar"></div>
        </div>

        <div
          className={magShowIng}
          style={{ backgroundImage: `url(${img})` }}
          ref={glass}
        ></div>
      </div>
    </div>
  )
}

export default Magnifying
